package logic

import (
	"context"
	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"grpc-common/live/types/live"
	"live/domain"
	"live/internal/svc"
	"strconv"
	"time"
)

type LiveLogic struct {
	ctx            context.Context
	svcCtx         *svc.ServiceContext
	liveTagDomain  *domain.LiveTagDomain
	liveRoomDomain *domain.LiveRoomDomain
	logx.Logger
}

func NewLiveLogicLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LiveLogic {
	return &LiveLogic{
		ctx:            ctx,
		svcCtx:         svcCtx,
		liveTagDomain:  domain.NewLiveTagDomain(svcCtx.DB),
		liveRoomDomain: domain.NewLiveRoomDomain(svcCtx.DB),
		Logger:         logx.WithContext(ctx),
	}
}

func (l *LiveLogic) GetAllTag(in *live.GetAllTagReq) (*live.GetAllTagResp, error) {
	tags, err := l.liveTagDomain.GetAllTag()
	if err != nil {
		return nil, err
	}
	var res []*live.Tag
	err = copier.Copy(&res, &tags)
	if err != nil {
		return nil, err
	}
	return &live.GetAllTagResp{
		Tags: res,
	}, nil
}

func (l *LiveLogic) GetCurrentLive(in *live.GetCurrentLiveReq) (*live.GetCurrentLiveResp, error) {
	// 先查询用户直播间是否已经存在
	ctx, canal := context.WithTimeout(context.Background(), 10*time.Minute)
	defer canal()
	room, err := l.liveRoomDomain.FindRoomByUserId(ctx, in.UserId)
	if room == nil {
		return nil, err
	}
	if room.Id == 0 {
		return nil, nil
	}
	// 如果存在查询用户标签
	tagId, err := strconv.ParseInt(room.TagId, 10, 64)
	if err != nil {
		return nil, err
	}
	tag, err := l.liveTagDomain.FindTagById(ctx, tagId)
	if err != nil {
		return nil, err
	}
	var res live.GetCurrentLiveResp
	err = copier.Copy(&res, &room)
	if err != nil {
		return nil, err
	}
	var t live.Tag
	err = copier.Copy(&t, &tag)
	if err != nil {
		return nil, err
	}
	res.Tags = append(res.Tags, &t)
	return &res, nil
}
